<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/4/10
 * Time: 0:25
 */

namespace app\api\controller\v1;


use app\api\validate\AddressNew;
use app\api\server\Token as TokenService;
use app\api\model\User as UserModel;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;

class Address
{
    public function createOrUpdateAddress()
    {
        $validate = new AddressNew();
        $validate->goCheck();
        //(new AddressNew())->goCheck();

        // 获取Token获取uid
        // 根据uid查找用户数据 判断用户是否存在 不存在跑出异常
        // 获取用户从客户端提交来的地址信息
        // 根据用户地址信息是否存在，从而判断是添加地址还是更新地址

        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);

        if (!$user) {
            throw new UserException();
        }
        $dataArray = $validate->getDataByRule(input('post.'));
        $userAddress = $user->address;
        if (!$userAddress) {
            // 创建
            $user->address()->save($dataArray);
        } else {
            // 更新
            $user->address->save($dataArray);
        }
        //return $user;
        return json(new SuccessMessage(), 201);
    }
}